<?php
/**
 * Created by PhpStorm.
 * User: 姚荣
 * Date: 2017/5/27
 * Time: 17:57
 */
//----------------------------------
// 基类
//----------------------------------

namespace app\common\controller;

use app\common\model\Auth;
use app\common\model\Cat;
use app\common\model\Role;
use think\Controller;
use think\Request;
use think\Cache;

class Base extends Controller
{
    protected $auth;

    public function _initialize()
    {
        if ((!session('?aid') || !session('?username')) && (!cookie('aid') || !cookie('username'))) {
            \app\home\controller\Index::msg('还未登录，请登录', url('home/Index/index'));
            exit();
        } else {
            if (cookie('aid') && cookie('username')) {
                session('aid', cookie('aid'));
                session('username', cookie('username'));
                session('roleid', cookie('roleid'));
            }
        }
        $request = Request::instance();//获取所有的请求对象
        $requesturl = strtolower('/' . $request->controller() . '/' . $request->action());//获取当前控制器与方法
        $this->auth = new Auth();
        $awhere = ['controler' => $requesturl];//获取上级控制器

        $topctrol = $this->auth->where($awhere)->value('topctrol');

        $this->assign('ctroname', $topctrol);//当前控制器的名称
        $this->assign('requesturl', $requesturl);//当前url域名后面的参数
        $this->assign('thisctrl', $request->action());//当前方法名
        $newcollist = $this->column();
        $this->assign('newcollist', $newcollist);
    }

    protected function column()
    {//按照权限显示对应一级栏目

        $authlist = $this->veryauth(3);
        $collist = $this->auth->order('sortid asc,id asc')->where('level=1 AND showif=1')->select();

        foreach ($collist as $key => $v) {
            if (session('aid') != 1) {
                if (in_array($v['controler'], $authlist)) {
                    $newcollist[$key] = ['controler' => $v['controler'], 'name' => $v['name'], 'level' => $v['level'], 'icon' => $v['icon'], 'id' => $v['id'], 'dlev' => ''];

                    $downwhere = ['level' => 2, 'showif' => 1, 'pid' => $v['id']];
                    $downcollist = $this->auth->order('sortid asc,id asc')->where($downwhere)->select();

                    foreach ($downcollist as $v1) {
                        if (in_array($v1['controler'], $authlist) && $v1['level'] == 2) {
                            $newcollist[$key]['dlev'][] = ['controler' => $v1['controler'], 'name' => $v1['name'], 'level' => $v1['level'], 'icon' => $v1['icon']];
                        }
                    }
                }
            } else {
                $newcollist[$key] = ['controler' => $v['controler'], 'name' => $v['name'], 'level' => $v['level'], 'icon' => $v['icon'], 'id' => $v['id'], 'dlev' => ''];

                $downwhere = ['level' => 2, 'showif' => 1, 'pid' => $v['id']];
                $downcollist = $this->auth->order('sortid asc,id asc')->where($downwhere)->select();

                foreach ($downcollist as $v1) {
                    if ($v1['level'] == 2) {
                        $newcollist[$key]['dlev'][] = ['controler' => $v1['controler'], 'name' => $v1['name'], 'level' => $v1['level'], 'icon' => $v1['icon']];
                    }
                }
            }
        }
        return $newcollist;
    }

    //验证权限
    protected function veryauth($msg = 0)
    {
        $request = Request::instance();//获取所有的请求对象
        if (session('aid') != 1) {
            $method = strtolower('/' . $request->controller() . '/' . $request->action());//获取当前控制器与方法

            $roleid = session('roleid');
            $role = new Role();
            $roleinfo = $role->find($roleid);
            $rolecotrol = $roleinfo['authlist'];
            $rctrwhere['id'] = ['in', $rolecotrol];
            $autharray = $this->auth->where($rctrwhere)->select();
            foreach ($autharray as $v) {
                $authlist[] = $v['controler'];
            }
            if ($msg == 3) {
                return $authlist;
            } else {
                if (!in_array($method, $authlist)) {
                    if ($msg == 0) {
                        \app\home\controller\Index::msg('没有权限', url('home/Index/index'));
                    } elseif ($msg == 1) {
                        $rel = ['rel' => 0, 'msg' => '没有权限'];
                        return json($rel);
                    }
                    exit();
                }
            }
        }

    }


    //图片上传
    public function uploadPhone()
    {
        //上传文件
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        //支持系统
        //头（“访问控制允许来源：×××××××”）；
        //如果任何其他站的标题/……
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // 做完预检CORS请求
        }

        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // 5分钟的执行时间
        @set_time_limit(5 * 60);
        // Settings
        $targetDir = '../public/upload_tmp';
        $uploadDir = '../public/upload';
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];

            if($_REQUEST['size']>3*1024*1024){
                     $ret = array('rel'=>0,'msg'=>'文件大小不能超过3M');
                     return json($ret);
                    }
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
            if($_FILES["file"]['size']>3*1024*1024){
                     $ret = array('rel'=>0,'msg'=>'文件大小不能超过3M');
                     return json($ret);
                    }
        } else {
            $fileName = uniqid("file_");
        }

        $hz = pathinfo($fileName, PATHINFO_EXTENSION);
        $filename = md5(time() . mt_rand(10, 99)) . "." . $hz; //新图片名称
        $filePath = $targetDir . '/' . $filename;
        $uploadPath = $uploadDir . '/' . $filename;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                $ret = array('rel' => 0, 'msg' => '临时目录不存在');
                return json($ret);
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            $ret = array('rel' => 0, 'msg' => '打开输出流失败');
            return json($ret);
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                $ret = array('rel' => 0, 'msg' => '移动上传的文件失败');
                return json($ret);
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                $ret = array('rel' => 0, 'msg' => '打开输入流失败');
                return json($ret);
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                $ret = array('rel' => 0, 'msg' => '打开输入流失败');
                return json($ret);
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                $ret = array('rel' => 0, 'result' => '打开输出流失败');
                return json($ret);
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }

        if ($uploadPath) {
            $ret = array('rel' => 1, 'msg' => "上传成功", 'result' => substr($uploadPath,9));
        } else {
            $ret = array('rel' => 0, 'msg' => '上传失败');
        }
        return json($ret);
    }




}